package response

import (
	"bookkeeping-gin/global"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
)

// Response 响应结构体
type Response struct {
	Code int    `json:"code"` // Code = 0 Success otherwise Failure
	Msg  string `json:"msg"`
	Data any    `json:"data"`
}

// Success 响应成功 code 为 0 表示成功
func Success(c *gin.Context, data any) {
	c.JSON(http.StatusOK, Response{
		0,
		"success",
		data,
	})
}

// Fail 响应失败 code 不为 0 表示失败
func Fail(c *gin.Context, code int, msg string) {
	c.JSON(http.StatusOK, &Response{
		code,
		msg,
		nil,
	})
}

func FailWithHttpCode(c *gin.Context, httpCode, errCode int, msg string) {
	c.JSON(httpCode, &Response{
		Code: errCode,
		Msg:  msg,
		Data: nil,
	})
}

// FailByError 失败响应 返回自定义错误的错误码、错误信息
func FailByError(c *gin.Context, error global.CustomError) {
	Fail(c, error.ErrorCode, error.ErrorMsg)
}

// ValidateFail 请求参数验证失败
func ValidateFail(c *gin.Context, msg string) {
	Fail(c, global.Errors.ValidateError.ErrorCode, msg)
}

// BusinessFail 业务逻辑失败
func BusinessFail(c *gin.Context, msg string) {
	Fail(c, global.Errors.BusinessError.ErrorCode, msg)
}

func TokenFail(c *gin.Context) {
	FailWithHttpCode(c, http.StatusUnauthorized, global.Errors.TokenError.ErrorCode, global.Errors.TokenError.ErrorMsg)
}

func ServerError(c *gin.Context, err any) {
	msg := "Internal Server Error"

	// 非生产环境
	if global.App.Config.App.Env != "production" && os.Getenv(gin.EnvGinMode) != gin.ReleaseMode {
		if e, ok := err.(error); ok {
			msg = e.Error()
		}
	}

	c.JSON(http.StatusInternalServerError, Response{
		http.StatusInternalServerError,
		msg,
		nil,
	})
	c.Abort()
}
